import { s_getSelectData, s_getTableInfo, s_stockIn } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { Button, Col, Divider, message, Row, Space, Tag } from "antd";
import moment from "moment";
import { useRef, useState } from "react";
import { useModel } from "@umijs/max";

const App:React.FC=()=>{
      const [taskCard,setTaskCard]=useState([]);

      const formRef_set=useRef<ProFormInstance>();
      const formRef_taskCard=useRef<ProFormInstance>();
      const actionRef_taskCard=useRef<ActionType>();
      const editableRef_taskCard=useRef<EditableFormInstance>();
      const { initialState, setInitialState } = useModel('@@initialState');

     interface DataType{
        // id,date,dep_name,order_code,operater_name,code,name,invstd,munit_name,craft,quantity,price,total
        rid?:number,taskcard_id?:number,taskcard_sno?:string,taskcard_name?:string,produce_order_code?:string,
        code?:string,name?:string,invstd?:string,munit_name?:string, quantity?:number, operate_time?:string,
        material_id?:number,source_produce_order_did?:number,quantity_fact?:number,quantity_done?:number,
     }

     const columns:ProColumns<DataType>[]=[
          //隐藏的列
         {dataIndex:'id',title:'ID',hidden:true,editable:false},
        //  {dataIndex:'source_taskcard_id', editable:false,title:'did'},
         {dataIndex:'material_id',hidden:true,editable:false},
         {dataIndex:'source_produce_order_did',hidden:true,editable:false},
          //显示的列
        {dataIndex:'rid',title:'rid',editable:false,hidden:true },
        
        {dataIndex:'taskcard_sno',title:'工序卡号',editable:false,width:'8%'},
        {dataIndex:'taskcard_name',title:'工序名称',editable:false},
        {dataIndex:'code',title:'SKU码',editable:false},
        {dataIndex:'name',title:'名称',editable:false,width:'15%'},
        {dataIndex:'invstd',title:'包装规格',editable:false,width:'15%'},
        {dataIndex:'munit_name',title:'单位',editable:false}, 
        {dataIndex:'quantity',title:'卡片数量',editable:false},
        // {dataIndex:'quantity_done',title:'卡片数量',editable:false},
        {dataIndex:'quantity_undone',title:'未报数量',editable:false,
                renderText(text, record, index, action) {
                   return <Tag color="red" style={{width:80,textAlign:'right'}}>
                    {(record.quantity?record.quantity:0)-(record.quantity_done?record.quantity_done:0)}
                    </Tag>
               },
              },
        {dataIndex:'quantity_fact',title:'实际产量',width:120},
        {dataIndex:'produce_time',title:'报产时间',valueType:'time',editable:false},
        {
         title:'操作',            
         fixed:'right',
         valueType:'option',
         width:80,
         editable:false,
         render:(text,record,_,action)=>[
            <a  key='del2'
                onClick={()=>{
                  var x:any[]=editableRef_taskCard.current?.getRowsData?.();
                  formRef_taskCard.current?.setFieldValue('editable',x.filter((item)=>item.rid!=record.rid));
                }}
            >
                删除
            </a>,
         ]
      }
    ];
 
    //保存产量信息
    async function saveReporting(){
       if(!formRef_set.current?.getFieldValue('warehouse_id')||!formRef_set.current?.getFieldValue('worker_id'))
          message.warning('保存失败！仓库和操作工必填');
       else if(formRef_taskCard.current?.getFieldValue('editable').length==0)
          message.warning('保存失败！没有扫描产量数据');
       else{ 
       var fset=formRef_set.current?.getFieldsValue();
       fset={...fset,stockin_time:moment(moment(fset.stockin_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
       var fdata=formRef_taskCard.current?.getFieldValue('editable');
    //    alert(JSON.stringify(fset));
    //    alert(JSON.stringify(fdata));
       fdata=fdata.map((t:any)=>({
        source_taskcard_id:t.source_taskcard_id,
        source_produce_order_did:t.source_produce_order_did,
        material_id:t.material_id,
        quantity:t.quantity_fact,
        // isend:t.isend,
        operate_time:moment(moment(t.produce_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
          }));

      //调用保存
    //   x_id,operater_id,etype,source,JSON.stringify(tdata)
      const x=await s_stockIn({x_id:1,operater_id:initialState?.currentUser?.userid,etype:1,source:'taskcard_reporting',
                               tdata:{source_type:3,mdata:fset,fdata}});
      if(x.success){
        message.success('保存产量成功');

      }else
        message.error('保存失败，请联系管理员');
    };
    };

   //  ========================================================================================================
    return <>
      <Row gutter={8}>
        <Col span={6}>
            <ProCard title='外发扫码' style={{height:800}}>
                <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:6}}
                      labelWrap formRef={formRef_set} initialValues={{
                         isreplace:1,stockin_time:moment(),
                      }} >
                       <Space.Compact>
                           <Button style={{height:50,fontSize:30,color:'red'}}>二维码</Button>
                           <ProFormText name='qrcode'  width={260} 
                             fieldProps={{
                                style:{height:50,fontSize:30,color:'red'},
                                 onKeyDown:async (e)=>{
                                   if(e.key=='Enter'){
                                       var v=e.target.value; 
                                       // source,x_id,id,type
                                       const x=await s_getTableInfo({source:'taskcard_reporting',x_id:1,id:v});
                                       // alert(JSON.stringify(x.data));
                                       if(x.data.length>0){
                                           var t=x.data[0];
                                           var fdata=formRef_taskCard.current?.getFieldValue('editable');
                                           fdata=fdata?fdata:[];
                                           fdata=[
                                                {rid:t.rid,source_taskcard_id:t.source_taskcard_id,
                                                 source_produce_order_did:t.source_produce_order_did,
                                                 material_id:t.material_id,taskcard_sno:t.taskcard_sno,
                                                 taskcard_name:t.taskcard_name,code:t.code,
                                                 name:t.name,invstd:t.invstd,munit_name:t.munit_name,
                                                 quantity:t.quantity,quantity_fact:t.quantity_fact,
                                                 produce_time:moment(),
                                                 quantity_done:t.quantity_done,
                                                //  isend:t.isend,
                                                },
                                                ...fdata];

                                           formRef_set.current?.setFieldsValue({
                                                                   qrcode:null,
                                                                   workcenter_id:t.workcenter_id,
                                                                   workgroup_id:t.workgroup_id,
                                                                   vendor:t.vendor,
                                                                  });         
                                           formRef_taskCard.current?.setFieldValue('editable',fdata);
                                           actionRef_taskCard.current?.startEditable(t.rid); 
                                         
                                       };
                                   };
                                },
                             }} />
                       </Space.Compact>

                       <Divider>扫码设置</Divider>
                       <ProFormRadio.Group name='isreplace' label='是否代扫' width={200}
                          options={[{value:0,label:'否'},{value:1,label:'是'}]} />
                       <ProFormSelect name='repworker_id' label='代扫人' width={200} 
                           showSearch
                           request={async ()=>{
                               const x=await s_getSelectData({x_id:1,source:'base_person'});
                               return x.data;}}
                       />
                       
                       <ProFormSelect name='workcenter_id' label='外发中心' width={200} 
                            showSearch
                            request={async ()=>{
                                const x=await s_getSelectData({x_id:1,source:'workcenter'});
                                return x.data;}}
                       />     
                       <ProFormSelect name='workgroup_id' label='外发商' width={200} 
                        showSearch
                        request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'workgroup'});
                            return x.data;}}
                       />    
                       <ProFormSelect name='worker_id' label='报产人' width={200}
                        rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'base_person'});
                            return x.data;}}
                       />
                       <ProFormSelect name='warehouse_id' label='仓库' width={200} 
                        rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'base2_ware'});
                            return x.data;}}
                       />    
                       <ProFormText name='vendor' label='外发商' width={200}
                         rules={[{required:true,message:'必填项'}]}
                       />              
                       <ProFormDatePicker name='stockin_time' label='产量日期' width={200} />
                       <ProFormSelect name='intype_id' label='入库类型' width={200}
                         showSearch
                         request={async ()=>{
                           const x=await s_getSelectData({x_id:1,source:'base_intype'});
                           return x.data;}}
                       />

                       <ProFormTextArea name='memo' label='备注' width={200}/>
                </ProForm>
            </ProCard>
        </Col>
        <Col span={18}>
        <ProCard title='外发扫码记录' style={{height:800}}
           extra={<Space>
                 <Button onClick={()=>saveReporting()}>生成外发报表和外发入库单</Button>
               </Space>}
       >
        <ProForm layout="horizontal" labelAlign="left" labelCol={{offset:0,span:6}} labelWrap submitter={false}
              formRef={formRef_taskCard}
        >
            <EditableProTable<DataType>
               name='editable'
               actionRef={actionRef_taskCard}
               editableFormRef={editableRef_taskCard}
               search={false}
               columns={columns}
            //    dataSource={tdata}
               options={false}
               rowSelection={{
                type:'radio',
               }}
               rowKey='rid'
               editable={{
                  type:'multiple',
               }}
               recordCreatorProps={false}
               scroll={{x:'100%'}}
              />
        </ProForm>
        </ProCard>
        </Col>
       
        </Row>
    </>;
};

export default App;